package com.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;

import com.wx.database.DatabaseDao;
import com.wx.entity.CarNumber;
import com.wx.entity.Office;
import com.wx.entity.User;
import com.wx.po.TextMessage;
import com.wx.util.MessageUtil;
import com.wx.util.SignUtil;

/**
 * Servlet implementation class WxServlet
 */
@WebServlet("/WxServlet")
public class WxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(SignUtil.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WxServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			logger.info("[signature: " + signature + "]<-->[timestamp: " + timestamp + "]<-->[nonce: " + nonce
					+ "]<-->[echostr: " + echostr + "]");
			response.getOutputStream().println(echostr);

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String path = request.getContextPath(); 
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		try {
			Map<String, Object> map = MessageUtil.xmlToMap(request);
			String fromUserName = map.get("FromUserName").toString(); // 发送方帐号（一个OpenID） 
			String toUserName = map.get("ToUserName").toString(); // 开发者微信号
			String msgType = map.get("MsgType").toString(); // text
//			String content = map.get("Content").toString(); // 文本消息内容

			DatabaseDao.addWork(fromUserName, msgType);
			
			int uid;
			List<Integer> uidlist;
			List<User> listUser;
			List<CarNumber> listCar;
			List<Office> listOffice;
			
			StringBuffer sb;
			
			String message = null;
			System.out.println("========" + msgType + "========");
			if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
				// 文本回复
				String content = map.get("Content").toString(); // 文本消息内容
				TextMessage text = new TextMessage();
				text.setFromUserName(toUserName);
				text.setToUserName(fromUserName);
				text.setMsgType(MessageUtil.MESSAGE_TEXT);
				text.setCreateTime((new Date()).getTime());
				
				String[] str = content.split("\\+");
				
				switch (str[0]) {
				case "1":
					content = MessageUtil.firstMenu();
					break;
				case "2":
					content = MessageUtil.secondMenu();
					break;
				case "3":
//					// 用户注册
//					content = "回复“33+用户名+联系电话”即可\r\n"
//							+ "例如：“33+hello+13111111111”";
					text.setMsgType(MessageUtil.MESSAGE_NEWS);
					text.setTitle("用户注册");
					text.setDescription("点击用户信息注册，即可轻松使用！");
					text.setImageUrl(basePath + "images/login.jpg");
					text.setUrl(basePath + "login.jsp?openid=" + fromUserName);
//					request.getSession().setAttribute("openid", fromUserName);
					System.out.println(request.getSession().getAttribute("openid"));
					break;
				case "4":
					// 系统管理
					if (DatabaseDao.queryPid(fromUserName) == 1) {
						content = MessageUtil.adminMenu();
					} else {
						content = "权限错误，请联系系统管理员处理";
					}
					break;
				case "5":
					// 普通管理
					if (DatabaseDao.queryPid(fromUserName) == 3) {
						content = "权限错误，请联系系统管理员处理";
					} else {
						content = MessageUtil.workMenu();
					}
					break;
				case "6":
					// 个人用户
					content = MessageUtil.userMenu();
					break;
				case "0":
					content = MessageUtil.menuText();
					break;
				case "33":
					if (str.length != 3) {
						content = "格式有误，请重新输入。\r\n";
					} else {
						if (DatabaseDao.addUser(str[1], str[2], fromUserName)) {
							content = "你好" + str[1] + "！您已经注册成功！";
						} else {
							content = "注册失败，请检查输入信息，或账号已存在，请联系管理员处理。";
						}
					}
					break;
				case "30":
					// 用户权限判断测试
					uidlist = DatabaseDao.openidQueryUid(fromUserName);
					switch (DatabaseDao.queryPid(fromUserName)) {
					case 1:
						content = "你好，你是超级管理员。\n";
						break;
					case 2:
						content = "你好，你是一般管理员。\n";
						break;
					case 3:
						content = "你好，你是普通用户。\n";
						break;
					default:
						content = "用户信息不存在或未知错误，请联系管理员处理。\n";
						break;	
					}
					if (uidlist != null && uidlist.size() > 0) {
						content += "您的ID为：" + uidlist.get(0);
					}
					break;
				case "40":
					// 获取所有已注册的用户
					listUser= DatabaseDao.queryUser();
					if (listUser != null && listUser.size() > 0) {
						sb = new StringBuffer();
						sb.append("已注册用户名单：\r\n"
								+ "ID\t用户名\n");
						for (int i = 0; i < listUser.size(); ++i) {
							sb.append(listUser.get(i).getUid() + "\t" + listUser.get(i).getUsername() + "\n");
						}
						content = sb.toString();
					} else {
						content = "系统中不存在已注册用户";
					}
					break;
				case "41":
					// 系统管理员管理
					content = MessageUtil.manageAdminMenu();
					break;
				case "410":
					// 查询所有系统管理员
					listUser = DatabaseDao.pidQueryUid(1);
					if (listUser != null && listUser.size() > 0) {
						sb = new StringBuffer();
						sb.append("系统管理员名单：\r\n"
								+ "ID\t用户名\t\n");
						for (int i = 0; i < listUser.size(); ++i) {
							sb.append(listUser.get(i).getUid() + "\t" + listUser.get(i).getUsername() + "\t\n");
						}
						content = sb.toString();
					} else {
						content = "系统管理员不存在！";
					}
					break;
				case "411":
					content = "回复“4110+用户ID”即可完成绑定！\n"
							+ "例如：\"4110+1\"";
					break;
				case "4110":
					uid = Integer.parseInt(str[1]);
					if (DatabaseDao.updatePid(1, uid)) {
						content = "更新完毕！";
					} else {
						content = "更新失败！请联系系统管理员！";
					}
					break;
				case "412":
					content = "回复“4120+用户ID”即可完成系统管理员解除绑定！\n"
							+ "例如：\"4120+1\"";
					break;
				case "4120":
					uid = Integer.parseInt(str[1]);
					if (DatabaseDao.updatePid(3, uid)) {
						content = "更新完毕！";
					} else {
						content = "更新失败！请联系系统管理员！";
					}
					break;
				case "42":
					content = MessageUtil.manageWorkerMenu();
					break;
				case "420":
					// 查询所有工作人员
					listUser = DatabaseDao.pidQueryUid(2);
					if (listUser != null && listUser.size() > 0) {
						sb = new StringBuffer();
						sb.append("工作人员名单：\r\n"
								+ "ID\t用户名\t\n");
						for (int i = 0; i < listUser.size(); ++i) {
							sb.append(listUser.get(i).getUid() + "\t" + listUser.get(i).getUsername() + "\t\n");
						}
						content = sb.toString();
					} else {
						content = "工作人员不存在！";
					}
					break;
				case "421":
					// 绑定工作人员
					content = "回复“4210+用户ID”即可完成绑定工作人员！\n"
							+ "例如：\"4210+1\"";
					break;
				case "4210":
					uid = Integer.parseInt(str[1]);
					if (DatabaseDao.updatePid(2, uid)) {
						content = "更新完毕！";
					} else {
						content = "更新失败！请联系系统管理员！";
					}
					break;
				case "422":
					// 解绑工作人员
					content = "回复“4220+用户ID”即可完成工作人员解除绑定！\n"
							+ "例如：\"4220+1\"";
					break;
				case "4220":
					uid = Integer.parseInt(str[1]);
					if (DatabaseDao.updatePid(3, uid)) {
						content = "解绑完成！";
					} else {
						content = "更新失败！请联系系统管理员！";
					}
					break;
				case "43":
					content = MessageUtil.manageUserMenu();
					break;
				case "430":
					//content = "<a href=\"/userlist.jsp\">点击查看</a>";
					text.setMsgType(MessageUtil.MESSAGE_NEWS);
					text.setTitle("点击查看用户信息");
					text.setDescription("用户注册信息列表");
					text.setImageUrl(basePath + "images/userinfo.jpg");
					text.setUrl(basePath + "userlist.jsp");
					break;
				case "61":
					// 个人信息管理
					content = MessageUtil.personalInfoManage();
					break;
				case "610":
					text.setMsgType(MessageUtil.MESSAGE_NEWS);
					text.setTitle("查看个人信息");
					text.setDescription("点击用户信息，即可轻松查看！");
					text.setImageUrl(basePath + "images/userinfo.jpg");
					text.setUrl(basePath + "login.jsp?openid=" + fromUserName);
//					request.getSession().setAttribute("openid", fromUserName);
					System.out.println(request.getSession().getAttribute("openid"));
					break;
				case "611":
					// 修改用户信息
					text.setMsgType(MessageUtil.MESSAGE_NEWS);
					text.setTitle("用户信息更改");
					text.setDescription("点击用户信息更改，即可轻松使用！");
					text.setImageUrl(basePath + "images/updateuser.jpg");
					text.setUrl(basePath + "updateUser.jsp?openid=" + fromUserName);
					break;
				case "62":
					content = MessageUtil.manageCarMenu();
					break;
				case "620":
					// 查看已绑定车牌
					uidlist = DatabaseDao.openidQueryUid(fromUserName);
					listCar = DatabaseDao.uidQueryCarnum(uidlist.get(0));
					if (listCar != null && listCar.size() > 0) {
						sb = new StringBuffer();
						sb.append("已绑定的车牌如下：\r\n");
						sb.append("ID\t车牌\n");
						for (int i = 0; i < listCar.size(); ++i) {
							sb.append(listCar.get(i).getCid() + "\t" + listCar.get(i).getCarnum() + "\n");
						}
						content = sb.toString();
					} else {
						content = "不好意思，您的名下没有绑定车牌，请绑定车牌后在尝试！";
					}
					break;
				case "621":
					content = "回复“6210+车牌号码”即可完成车牌绑定！\n"
							+ "例如：\"6210+粤AHG123\"";
					break;
				case "6210":
					// 绑定车牌
					uidlist = DatabaseDao.openidQueryUid(fromUserName);
					content = DatabaseDao.addCar(uidlist.get(0), str[1]);
					break;
				case "622":
					content = "回复“6220+车牌ID”即可删除车牌绑定！\n"
							+ "例如：\"6220+1\"";
					break;
				case "6220":
					// 删除已绑定的车牌
					content = DatabaseDao.deleteCar(Integer.valueOf(str[1]));
					break;
				case "63":
					content = MessageUtil.infoQuery();
					break;
				case "630":
					uidlist = DatabaseDao.openidQueryUid(fromUserName);
					listOffice = DatabaseDao.queryOffice(uidlist.get(0));
					if (listOffice != null && listOffice.size() > 0) {
						sb = new StringBuffer();
						sb.append("车辆所有出入记录：\r\n");
						sb.append("车牌号码\t记录时间\r\n");
						for (int i = 0; i < listOffice.size(); ++i) {
							sb.append(listOffice.get(i).getCarNumber() + " " + listOffice.get(i).getDate());
						}
						content = sb.toString();
					} else {
						content = "暂无进入记录，请稍后查询！";
					}
					break;
				case "631":
					content = "回复“6310+车牌ID”即可删除车牌绑定！\n"
							+ "例如：\"6310+1\"";
					break;
				case "6310":
					uidlist = DatabaseDao.openidQueryUid(fromUserName);
					listOffice = DatabaseDao.queryOffice(uidlist.get(0));
					if (listOffice != null && listOffice.size() > 0) {
						sb = new StringBuffer();
						sb.append("车辆所有出入记录：\r\n");
						sb.append("车牌号码\t记录时间\r\n");
						for (int i = 0; i < listOffice.size(); ++i) {
							sb.append(listOffice.get(i).getCarNumber() + " " + listOffice.get(i).getDate());
						}
						content = sb.toString();
					} else {
						content = "暂无进入记录，请稍后查询！";
					}
					break;
				default:
					content = "回复有误，请回复“0”返回主菜单。";
					break;
				}
				switch (text.getMsgType()) {
				case MessageUtil.MESSAGE_TEXT:
					text.setContent(content);
					message = MessageUtil.textMessageToXml(text);
					break;
				case MessageUtil.MESSAGE_NEWS:
					message = MessageUtil.graphicToXml(text);
					break;
				default:
					break;
				}
			} else if (MessageUtil.MESSAGE_EVENT.equals(msgType)) {
				// 事件
				String eventType = (String) map.get("Event");
				if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
					//首次关注
					message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
				}
			}
			
			System.out.println(message);
			out.print(message);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("数据库错误");
		} finally {
			out.close();
		}
	}

}
